import requests
import json
import time
import sys


def send_stream_data(client_id, data):
    """
    向指定客户端发送流式数据
    """
    url = f"http://localhost:8000/push/{client_id}"
    headers = {"Content-Type": "application/json"}

    try:
        response = requests.post(
            url,
            data=json.dumps(data),
            headers=headers
        )
        return response.json()
    except Exception as e:
        print(f"Error sending data: {e}")
        return {"status": "error", "message": str(e)}


def list_clients():
    """
    获取所有活跃客户端列表
    """
    url = "http://localhost:8000/clients"
    try:
        response = requests.get(url)
        return response.json()
    except Exception as e:
        print(f"Error listing clients: {e}")
        return {"clients": []}


if __name__ == "__main__":
    # 首先获取活跃客户端列表
    clients_info = list_clients()
    print("Active clients:", clients_info)

    if not clients_info.get("clients"):
        print("No active clients found. Please ensure the frontend is connected.")
        sys.exit(1)

    # 使用第一个客户端ID
    client_id = clients_info["clients"][0]
    print(f"Using client ID: {client_id}")

    # 模拟发送一些流式数据
    for i in range(10):
        data = {
            "message": f"Stream data chunk {i}",
            "timestamp": time.time(),
            "chunk_id": i,
            "type": "data"
        }

        result = send_stream_data(client_id, data)
        print(f"Sent chunk {i}: {result}")

        time.sleep(1)  # 模拟数据间隔